package com.lfy.kcat.content.biz.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.lfy.kcat.content.biz.DramaHomeService;
import com.lfy.kcat.content.domain.ActorRoleInfoEntity;
import com.lfy.kcat.content.domain.Categories;
import com.lfy.kcat.content.domain.Episodes;
import com.lfy.kcat.content.domain.Tags;
import com.lfy.kcat.content.domain.bo.DramasBo;
import com.lfy.kcat.content.domain.vo.DramasVo;
import com.lfy.kcat.content.mapper.EpisodesMapper;
import com.lfy.kcat.content.service.DramaActorsService;
import com.lfy.kcat.content.service.DramaCategoriesService;
import com.lfy.kcat.content.service.DramaTagsService;
import com.lfy.kcat.content.service.IDramasService;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.dto.PageReqDTO;
import org.dromara.common.core.dto.home.HomeDramaEpisodesDTO;
import org.dromara.common.core.dto.home.HomeDramaEpisodesDTO.DramaInfoDTO;
import org.dromara.common.core.dto.home.HomeDramaEpisodesDTO.StatisticsDTO;
import org.dromara.common.core.dto.home.HomeDramaInfoDTO;
import org.dromara.common.core.dto.home.HomeFeaturedDTO;
import org.dromara.common.core.dto.home.HomeFeaturedDTO.EpisodesDTO.DramaDTO;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author leifengyang
 * @version 1.0
 * @date 2025/9/17 11:24
 * @description:
 */
@Slf4j
@Service
public class DramaHomeServiceImpl implements DramaHomeService {


    @Autowired
    IDramasService dramasService;

    @Autowired
    DramaCategoriesService dramaCategoriesService;

    @Autowired
    DramaActorsService dramaActorsService;

    @Autowired
    EpisodesMapper episodesMapper;

    @Autowired
    DramaTagsService dramaTagsService;



    @Override
    public HomeFeaturedDTO getHomeFeatureDrama(PageReqDTO pageReqVo) {
        HomeFeaturedDTO featuredDTO = new HomeFeaturedDTO();
        //1、组装 episodes 数据
        // 1)、查询所有短剧; 并查询这个短剧的第一集的id;
        PageQuery query = new PageQuery(pageReqVo.getPageSize(),pageReqVo.getPage());
        // 后续需要加两个条件  status=1 and audi_status=1
        DramasBo dramasBo = new DramasBo();
        dramasBo.setStatus(1L);
        dramasBo.setAuditStatus(1L);
        //分页查询
        TableDataInfo<DramasVo> table = dramasService.queryPageList(dramasBo, query);


        //构造所有短剧信息流、短剧基本信息及所在的某一集数据
        List<HomeFeaturedDTO.EpisodesDTO> episodes = table.getRows().stream()
            .parallel()
            .map(dramasVo -> {
                HomeFeaturedDTO.EpisodesDTO dto = new HomeFeaturedDTO.EpisodesDTO();
                Episodes episodes1 = episodesMapper.getDramaInfoFlowsEpisode(dramasVo.getDramaId());
                //信息流所在的剧集
                dto.setEpisode(episodes1.getEpisodeId().toString());
                dto.setTitle("第"+episodes1.getEpisodeNumber()+"集");
                dto.setDramaTitle(dramasVo.getTitle());
                dto.setDescription(dramasVo.getDescription());
                dto.setDuration(dramasVo.getTotalDuration() + "");
                dto.setLikeCount(dramasVo.getLikeCount().intValue());
                //TODO 远程调用 互动服务 拿到点赞数量
                dto.setFavoriteCount(0);
                dto.setCommentCount(dramasVo.getCommentCount().intValue());
                //播放量
                dto.setViewCount(dramasVo.getPlayCount().intValue());

                //TODO 远程调用 互动服务 拿到点赞数量
                dto.setIsLiked(false);
                //TODO 远程调用 互动服务 拿到是否收藏
                dto.setIsFavorited(false);
                //评分统计
                dto.setRatingCount(0);

                //当前短剧信息
                DramaDTO dramaDTO = new DramaDTO();
                dramaDTO.setId(dramasVo.getDramaId().toString());
                dramaDTO.setTitle(dramasVo.getTitle());
                dramaDTO.setCover(dramasVo.getCover());
                //获取短剧标签
                List<Tags> tags = dramaTagsService.getDramaTagsByDramaId(dramasVo.getDramaId());

                List<String> tagList = tags.stream().map(Tags::getName).toList();
                dramaDTO.setTags(tagList);
                //短剧分类
                List<Categories> categories = dramaCategoriesService
                    .getDramasCategoryInfo(dramasVo.getDramaId());
                List<String> list = categories.stream().map(Categories::getName).toList();
                // 古装, 剧情, 历史
                dramaDTO.setCategory(String.join(",",list));
                dramaDTO.setIsNew(false);
                dramaDTO.setIsPopular(false);

                dramaDTO.setDirector(dramasVo.getDirector());

                //短剧演员
                List<ActorRoleInfoEntity> actors = dramaActorsService.getDramaActorInfo(dramasVo.getDramaId());

                List<DramaDTO.ActorsDTO> actorsDTOS = actors.stream().map(ac -> {
                    DramaDTO.ActorsDTO actorsDTO = new DramaDTO.ActorsDTO();
                    actorsDTO.setName(ac.getActorName());
                    actorsDTO.setRole(ac.getRoleName());
                    actorsDTO.setAvatar(ac.getAvatar());
                    return actorsDTO;
                }).toList();
                dramaDTO.setActors(actorsDTOS);


                dto.setDrama(dramaDTO);
                dto.setHotScore(0);
                //短剧标签
                dto.setEpisodeTags(Lists.newArrayList());
                dto.setCover(dramasVo.getCover());
                dto.setVideoUrl(dramasVo.getTrailerInfoflowUrl());

                return dto;
            }).toList();

        featuredDTO.setEpisodes(episodes);





        //2）、 分页
        HomeFeaturedDTO.PaginationDTO dto = new HomeFeaturedDTO.PaginationDTO();
        dto.setPage(pageReqVo.getPage());
        dto.setPageSize(pageReqVo.getPageSize());
        dto.setTotal(Integer.parseInt(table.getTotal()+""));

        //总页码   21/10 = 2.222  = 3
        dto.setTotalPages((int) Math.ceil((double) table.getTotal() / pageReqVo.getPageSize()));
        //是否有更多
        dto.setHasMore(dto.getPage() < dto.getTotalPages());

        featuredDTO.setPagination(dto);

        log.info("首页精选视频数据准备完成, {}", featuredDTO);
        return featuredDTO;
    }

    @Override
    public HomeDramaEpisodesDTO getDramaEpisodesInfo(Long dramaId) {

        HomeDramaEpisodesDTO dto = new HomeDramaEpisodesDTO();
        dto.setDramaId(dramaId.toString());

        //1、短剧信息
        DramasVo dramasVo = dramasService.queryById(dramaId);
        DramaInfoDTO infoDTO = getDramaInfoDTO(dramaId, dramasVo);
        dto.setDramaInfo(infoDTO);


        //2、剧集信息

        List<Episodes> episodes = episodesMapper.selectList(Wrappers.lambdaQuery(Episodes.class)
            .eq(Episodes::getDramaId, dramaId));
        List<HomeDramaEpisodesDTO.EpisodesDTO> list = episodes.stream().map(episode -> {
            HomeDramaEpisodesDTO.EpisodesDTO episodesDTO = new HomeDramaEpisodesDTO.EpisodesDTO();
            episodesDTO.setCid(dramaId.toString());
            episodesDTO.setEpisode(episode.getEpisodeId().toString());
            episodesDTO.setTitle("第" + episode.getEpisodeNumber() + "集");
            episodesDTO.setDramaTitle(dramasVo.getTitle());
            episodesDTO.setDescription(dramasVo.getDescription());
            episodesDTO.setDuration(episode.getDuration().toString());
            //TODO 互动计数
            episodesDTO.setLikeCount(episode.getLikeCount().intValue());
            //TODO 喜欢收藏
            episodesDTO.setFavoriteCount(0);
            //TODO 播放量
            episodesDTO.setViewCount(episode.getPlayCount().intValue());
            episodesDTO.setCommentCount(episode.getCommentCount().intValue());
            //TODO 互动服务
            episodesDTO.setIsLiked(false);
            //TODO 互动服务
            episodesDTO.setIsFavorited(false);
            episodesDTO.setStatus(episode.getStatus().toString());
            episodesDTO.setIsVip(episode.getIsFree() == 1);

            episodesDTO.setReleaseDate(DateUtils.formatDate(dramasVo.getReleaseDate()));
            episodesDTO.setDramaId(dramaId.toString());

            //TODO 播放服务：进度
            episodesDTO.setProgress(0);
            //TODO 播放服务：最后一次观看时间
            episodesDTO.setLastWatchTime("");
            episodesDTO.setRating(0.0D);
            episodesDTO.setRatingCount(0);
            episodesDTO.setIsWatched(false);
            episodesDTO.setIsCurrentWatch(false);
            episodesDTO.setCover(dramasVo.getCover());
            //前端没有带清晰度参数
            String quality = "720";
            if ("720".equals(quality)) {
                episodesDTO.setVideoUrl(episode.getVideoUrlSd());
            } else {
                episodesDTO.setVideoUrl(episode.getVideoUrlHd());
            }
            return episodesDTO;
        }).toList();
        dto.setEpisodes(list);


        //3、指标信息（细化细节）
        StatisticsDTO statisticsDTO = new StatisticsDTO();
        statisticsDTO.setTotal(dramasVo.getTotalEpisodes().intValue());
        statisticsDTO.setAvailableCount(dramasVo.getTotalEpisodes().intValue());
        statisticsDTO.setComingCount(0);
        statisticsDTO.setWatchedCount(0);
        statisticsDTO.setUnwatchedCount(0);
        dto.setStatistics(statisticsDTO);

        dto.setSort("asc");
        dto.setStatus("all");

        log.info("准备获取短剧所有剧集数据：{}",dramaId);
        return dto;
    }

    @Override
    public HomeDramaInfoDTO getDramaInfo(Long dramaId) {



        DramasVo dramasVo = dramasService.queryById(dramaId);
        HomeDramaInfoDTO dto = new HomeDramaInfoDTO();
        dto.setCover(dramasVo.getCover());
        dto.setTitle(dramasVo.getTitle());
        dto.setViewCount(dramasVo.getPlayCount().intValue());
        dto.setLikeCount(dramasVo.getLikeCount().intValue());

        //演员
        List<ActorRoleInfoEntity> actorInfo = dramaActorsService.getDramaActorInfo(dramaId);

        List<HomeDramaInfoDTO.ActorsDTO> list = actorInfo.stream().map(actor -> {
            HomeDramaInfoDTO.ActorsDTO actorsDTO = new HomeDramaInfoDTO.ActorsDTO();
            actorsDTO.setName(actor.getActorName());
            actorsDTO.setRole(actor.getRoleName());
            actorsDTO.setAvatar(actor.getAvatar());
            return actorsDTO;
        }).toList();

        dto.setActors(list);
        dto.setDescription(dramasVo.getDescription());
        dto.setTotalEpisodes(dramasVo.getTotalEpisodes().intValue());

        return dto;
    }

    @NotNull
    private DramaInfoDTO getDramaInfoDTO(Long dramaId, DramasVo dramasVo) {
        DramaInfoDTO infoDTO = new DramaInfoDTO();
        infoDTO.setId(dramasVo.getDramaId().toString());
        infoDTO.setTitle(dramasVo.getTitle());
        infoDTO.setCover(dramasVo.getCover());
        //总集数
        infoDTO.setTotalEpisodes(dramasVo.getTotalEpisodes().intValue());
        infoDTO.setCurrentEpisode(dramasVo.getCurrentEpisodes().intValue());
        infoDTO.setCurrentWatchEpisode(1);
        infoDTO.setIsCompleted(false);
        //TODO 获取当前短剧是否是追剧记录
        infoDTO.setIsFollowing(false);
        //短剧标签
        //获取短剧标签
        List<Tags> tags = dramaTagsService.getDramaTagsByDramaId(dramaId);
        List<String> tagList = tags.stream().map(Tags::getName).toList();
        infoDTO.setTags(tagList);
        //短剧描述
        infoDTO.setDescription(dramasVo.getDescription());
        return infoDTO;
    }
}
